// @ts-ignore
import db from "node-little-db";
import type { UserInfoFace } from "@/types/user";
type User = Record<string, UserInfoFace>;
type OnlineWs = Record<string, any>;
const rootPath =__dirname //process.cwd();
const sqlUrl = rootPath + "../../db";
const user: User = db.use("user",{
  path:sqlUrl
});

class UserSql {
  chatUsers: UserInfoFace[];
  sqlUrl: string;
  onlineWs: OnlineWs;
  constructor() {
    this.chatUsers = [];
    this.onlineWs = {};
  }
  getIndex(userId: string) {
    const index = this.chatUsers.findIndex((v) => v.userId == userId);
    return index;
  }
  // 在线
  addOnline(user: UserInfoFace, ws: any) {
    if (!user || !user.userId) return;
    this.onlineWs[user.userId] = ws;
  }
  /**
   * 离线
   * @param userId
   */
  offline(userId: string) {
    this.onlineWs[userId] = undefined;
    const index = this.getIndex(userId);
    if (index !== -1) {
      this.chatUsers.splice(index);
    }
  }
  // 进来就登录
  initLogin(path: string, ws: any): Promise<UserInfoFace> {
    return new Promise((resolve, reject) => {
      if (!path) return;
      const id = path.replace(/\//g, "");
      let userInfo = this.getUserInfo(id, true);

      this.addOnline(userInfo, ws);
      this.sendUserInfo(id);
      resolve(userInfo);
    });
  }

  getLength() {
    return this.chatUsers.length;
  }
  updateJson() {}
  addUser(userId: string) {
    if (!user[userId]) {
      user[userId] = {
        userId,
        userName: `luren${new Date().getTime().toString()}`,
        isNew: true,
      };
    }
    return user[userId];
  }
  getUserInfo(userId: string, isregister = true): UserInfoFace | undefined {
    let users = this.chatUsers.find((v) => v.userId == userId);
    if (isregister && !users) {
      users = this.addUser(userId);
    }

    return users;
  }
  /**
   * 通知返回用户信息
   * @param userId
   */
  sendUserInfo(userId: string) {
    const data = this.getUserInfo(userId);

    if (data) {
      const { ws, ...arg } = data;
      const obj1 = {
        type: "userInfo",
        ...arg,
      };
      this.onlineWs[userId]?.send(JSON.stringify(obj1));
    }
  }

  editName(userId: string, name: string, isTip = true) {
    const index = this.chatUsers.findIndex((v) => v.userId == userId);
    if (index !== -1) {
      const oldName = this.chatUsers[index].userName || "路人";
      this.chatUsers[index].userName = name;
      const obj = {
        type: "system",
        name: "系统",
        msg: "你成功改名字为>" + name,
      };
      if (isTip) {
        this.chatUsers[index]?.ws.send(JSON.stringify(obj));
      }

      this.sendUserInfo(userId);

      return `${oldName}改名为${name}`;
    }
  }
  editSex(userId: string, sex: number) {
    const index = this.chatUsers.findIndex((v) => v.userId == userId);
    if (index !== -1) {
      this.chatUsers[index].sex = sex;
      this.updateJson();
    }
  }
}
export default UserSql;
